﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Query;
using Happy.Query.Filters;

namespace Happy.Application.Query
{
    /// <summary>
    /// 客户端传递的动态筛选器分组。
    /// </summary>
    public sealed class DynamicFilterGroup
    {
        /// <summary>
        /// 连接器。
        /// </summary>
        public Connector Connector { get; set; }

        /// <summary>
        /// 子筛选器分组。
        /// </summary>
        public DynamicFilterGroup[] Groups { get; set; }

        /// <summary>
        /// 子筛选器。
        /// </summary>
        public DynamicFilter[] Filters { get; set; }

        internal WhereClause ToWhereClause()
        {
            var filterDefinition = new FilterDefinition(this.ToFilter());

            return filterDefinition.BuildWhereClause();
        }

        internal IFilter ToFilter()
        {
            var filters = this.GetFilters();

            return new FilterGroup(this.Connector, filters);
        }

        private IFilter[] GetFilters()
        {
            var filters = new List<IFilter>();

            if (this.Groups != null)
            {
                filters.AddRange(this.Groups.Select(x => x.ToFilter()));
            }

            if (this.Filters != null)
            {
                filters.AddRange(this.Filters.Select(x => x.ToFilter()));
            }

            return filters.ToArray();
        }
    }
}
